import Vue from 'vue'
import VueRouter from 'vue-router'
// @符号在路径中表示 src 的绝对路径,脚手架为我们配置的
import Reg from '@/views/Reg/Reg.vue'
import Login from '../views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置,即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}
// 路由规则数组
const routes = [
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    // 重新定向到 /home
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 使用导航守卫,进行未登录dev权限控制
router.beforeEach((to, from, next) => {
  const whiteList = ['/login', '/reg']
  if (!store.state.user.token && !whiteList.includes(to.path)) {
    // 给用户一个友好的提示
    Vue.prototype.$message.error('您没有登录!!!')
    return next('/login')
  }
  next()
})
export default router
